package com.chinaisafe.user.service.impl;

import com.chinaisafe.user.entity.SysMenu;
import com.chinaisafe.user.mapper.SysMenuMapper;
import com.chinaisafe.user.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaisafe.user.util.MenuTreeBuilder;
import com.chinaisafe.user.vo.request.SysMenuReqVO;
import com.chinaisafe.user.vo.response.SysMenuRespVO;
import org.springframework.stereotype.Service;
import com.chinaisafe.base.common.exception.BizException;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
 * SysMenuServiceImpl
 * Description：菜单(资源)服务实现类
 *
 * @author tby
 * @date 2024-07-11 17:32:41
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Override
    public List<SysMenuRespVO> getList(SysMenuReqVO sysMenuReqVO) {

        List<SysMenuRespVO> sysMenuResps = baseMapper.queryList(sysMenuReqVO);
        return MenuTreeBuilder.buildTrees(sysMenuResps);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysMenuRespVO add(SysMenuReqVO sysMenuReqVO) {
        // 新增和编辑逻辑相同的情况下 直接调用新增或编辑方法
        return this.addOrUpdate(sysMenuReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysMenuRespVO update(SysMenuReqVO sysMenuReqVO) {
        // 新增和编辑逻辑相同的情况下 直接调用新增或编辑方法
        return this.addOrUpdate(sysMenuReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysMenuRespVO addOrUpdate(SysMenuReqVO sysMenuReqVO) {
        Long sysMenuId = sysMenuReqVO.getId();
        if (sysMenuId != null){
            // 编辑
            SysMenu sysMenu = baseMapper.selectById(sysMenuId);
            Optional.ofNullable(sysMenu).orElseThrow(() -> BizException.build("未找到要修改的菜单(资源)信息"));
        }
        SysMenu sysMenu2Save = sysMenuReqVO.convertToEntity();
        boolean success = this.saveOrUpdate(sysMenu2Save);
        if (success) {
            return SysMenuRespVO.convertFromEntity(sysMenu2Save, null, null);
        } else {
            BizException.throwException("操作失败，请刷新后重试");
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(Long[] sysMenuIds) {
        if (sysMenuIds.length > 0) {
            this.removeByIds(Arrays.asList(sysMenuIds));
        }
    }
}
